package client;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private BufferedReader userMessage;

	public Client(String host, int port) throws UnknownHostException, IOException {
            this.socket = new Socket(host, port);
            this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            this.out = new PrintWriter(socket.getOutputStream());
            this.userMessage = new BufferedReader(new InputStreamReader(System.in));
	}
	
	void run() {
		try{
			System.out.println("Connected to " + this.socket.getRemoteSocketAddress());
			login();
			getChannel();

                        new Thread(new Receiver(socket,in)).start();
                        
                        while(true){
				String message = "";
				while(message.equals(""))  {								
					try {
						message =  this.userMessage.readLine();
						
					} catch (IOException e) {
						System.out.println();
					}
				}
                                send(message);
			}
		}catch(Exception e){
			System.out.println("Connection was destroyed!!");
		}finally{
			System.out.println("WENT AWAY!!!!!");
			try{
				if(this.socket != null)this.socket.close();
				System.exit(0);
			}
			catch(IOException e){
				System.out.println("Connection was destroyed!!");

			}
		}
		
	}
	
	private void login() throws IOException{
		String messageFromServer = "";
		System.out.println("Enter your login: ");
		while(!messageFromServer.startsWith("HELLO")){
			send(this.userMessage.readLine());
			messageFromServer = this.in.readLine();
			System.out.println(messageFromServer);
		}
	}
	
	private void getChannel() throws IOException{
		System.out.println(this.in.readLine());
		String messageFromServer = this.in.readLine();
		System.out.println(messageFromServer);
		while(!messageFromServer.startsWith("You entered")){
			send(this.userMessage.readLine());
			messageFromServer = this.in.readLine();
			System.out.println(messageFromServer);
		}
	}

 	private void send(String message){
		this.out.write(message + "\n");
		this.out.flush();
	}

 	
	public static void main(String args[])	{
		try {
			new Client("localhost", 3000).run();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}



